package com.pzh.assignment.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pzh.assignment.common.bean.GlobalConstant;
import com.pzh.assignment.common.bean.Result;
import com.pzh.assignment.common.bean.param.LoginParam;
import com.pzh.assignment.common.bean.vo.LoginVO;
import com.pzh.assignment.common.bean.vo.VerifyCodeVO;
import com.pzh.assignment.common.shiro.bean.JwtToken;
import com.pzh.assignment.common.utils.RedisUtil;
import com.pzh.assignment.common.utils.VerifyCodeUtil;
import com.pzh.assignment.entity.Groups;
import com.pzh.assignment.entity.Role;
import com.pzh.assignment.entity.User;
import com.pzh.assignment.service.IGroupsService;
import com.pzh.assignment.service.IRoleService;
import com.pzh.assignment.service.IUserService;
import com.pzh.assignment.common.utils.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * @description: 登录退出逻辑实现
 * @author pengzhihao
 * @date 2022/3/29
 */
@RestController
public class AccountController {

    @Autowired
    IUserService userService;
    @Autowired
    IRoleService roleService;
    @Autowired
    IGroupsService groupsService;

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    RedisUtil redisUtil;


    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginParam param, HttpServletResponse response) {
        //验证码校验
        if (verify(param.getKey(), param.getCode())){
            return Result.fail("验证码错误");
        }
        User user = userService.getOne(new QueryWrapper<User>().eq("account", param.getAccount()));
        Assert.notNull(user, "账户不存在");
        Assert.isTrue(user.getPassword().equals(param.getPassword()), "密码错误");
        Role role = roleService.getById(user.getRoleId());
        Groups groups = groupsService.getById(user.getGroupId());
        MapBuilder<String, String> builder = MapUtil.builder();
        String token = jwtUtils.generateToken(builder
                .put("id", user.getId().toString())
                .put("username", user.getUsername())
                .put("role", role.getName())
                .map());
        SecurityUtils.getSubject().login(new JwtToken(token));
        Date expireTime = jwtUtils.getExpireTime();
//        response.setHeader("Authorization",token);
        response.setHeader("Access-Control-Expose-Headers","Authorization");
        return Result.success(LoginVO.valueOf(user, role.getName(), groups.getName(), token, expireTime));
    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout(){
        SecurityUtils.getSubject().logout();
        return Result.success(null);
    }

    /**
     * @description: 生成验证码
     * @param:
     * @return: com.pzh.assignment.common.bean.Result
     * @author pengzhihao
     * @date: 2022/3/29
     */
    @GetMapping("/getVerifyCode")
    public Result getVerifyCode() throws IOException {
        String key = UUID.randomUUID().toString();
        //生成验证码，4位
        String verifyCode = VerifyCodeUtil.generateVerifyCode(GlobalConstant.VERIFYCODE_NUM);
        //生成验证码对应图片
        String base64Img = VerifyCodeUtil.outputImage(GlobalConstant.VERIFYCODE_IMG_WIDTH, GlobalConstant.VERIFYCODE_IMG_HIGH, verifyCode);
        //将生成的数据存储在redis中
        redisUtil.hset(GlobalConstant.VERIFYCODE_KEY, key, verifyCode);
        return Result.success(VerifyCodeVO.valueOf(key, base64Img));
    }

    /**
     * @description: 验证码校验
     * @param: key
     * @param: code
     * @return: boolean
     * @author pengzhihao
     * @date: 2022/3/29
     */
    private boolean verify(String key, String code) {
        //从redis中获取key对应的验证码
        String verifyCode = (String)redisUtil.hget(GlobalConstant.VERIFYCODE_KEY, key);
        if (verifyCode == null || verifyCode.equalsIgnoreCase(code)){
            return false;
        }
        return true;
    }

}
